const express = require('express');
const router = express.Router();
const orderService = require('../services/orderService');

/**
 * 创建新订单
 * POST /api/orders
 */
router.post('/', async (req, res) => {
  try {
    const { items, userInfo } = req.body;

    if (!items || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '订单商品不能为空'
      });
    }

    if (!userInfo || !userInfo.name || !userInfo.phone) {
      return res.status(400).json({
        success: false,
        message: '用户信息不完整'
      });
    }

    const totalPrice = await orderService.calculateTotalPrice(items);

    const orderData = {
      items,
      totalPrice,
      userInfo
    };

    const order = await orderService.createOrder(orderData);

    const estimatedTime = new Date(Date.now() + 45 * 60 * 1000).toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      hour: '2-digit',
      minute: '2-digit'
    });

    // 实时推送订单到后厨窗口
    const io = req.app.get('io');
    if (io) {
      const orderDetails = {
        id: order.id,
        items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
        totalPrice: order.total_price,
        userInfo: typeof order.user_info === 'string' ? JSON.parse(order.user_info) : order.user_info,
        status: order.status,
        createdAt: order.created_at
      };
      
      io.to('kitchen').emit('new-order', orderDetails);
      console.log('订单已推送到后厨:', order.id);
    }

    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: {
        orderId: order.id,
        totalPrice: order.total_price,
        estimatedTime,
        status: order.status,
        smsNotification: '已发送至手机'
      }
    });
  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '订单创建失败，请稍后重试'
    });
  }
});

/**
 * 获取订单详情
 * GET /api/orders/:orderId
 */
router.get('/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params;

    const order = await orderService.getOrderById(orderId);

    res.json({
      success: true,
      data: {
        id: order.id,
        items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
        totalPrice: order.total_price,
        userInfo: typeof order.user_info === 'string' ? JSON.parse(order.user_info) : order.user_info,
        status: order.status,
        createdAt: order.created_at
      }
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(404).json({
      success: false,
      message: error.message || '订单不存在'
    });
  }
});

/**
 * 查询用户订单列表
 * GET /api/orders/user/:phone
 */
router.get('/user/:phone', async (req, res) => {
  try {
    const { phone } = req.params;
    const { limit = 10, offset = 0 } = req.query;

    const orders = await orderService.getOrdersByPhone(
      phone,
      parseInt(limit),
      parseInt(offset)
    );

    const formattedOrders = orders.map(order => ({
      id: order.id,
      items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
      totalPrice: order.total_price,
      status: order.status,
      createdAt: order.created_at
    }));

    res.json({
      success: true,
      data: formattedOrders,
      total: formattedOrders.length
    });
  } catch (error) {
    console.error('查询订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '查询订单失败，请稍后重试'
    });
  }
});

/**
 * 获取后厨订单列表
 * GET /api/orders/kitchen/list
 */
router.get('/kitchen/list', async (req, res) => {
  try {
    const { status, startDate, endDate, limit = 50, offset = 0 } = req.query;

    const filters = {
      status,
      startDate,
      endDate,
      limit: parseInt(limit),
      offset: parseInt(offset)
    };

    const orders = await orderService.getAllOrders(filters);

    const formattedOrders = orders.map(order => ({
      id: order.id,
      items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
      totalPrice: order.total_price,
      userInfo: typeof order.user_info === 'string' ? JSON.parse(order.user_info) : order.user_info,
      status: order.status,
      createdAt: order.created_at,
      updatedAt: order.updated_at
    }));

    res.json({
      success: true,
      data: formattedOrders,
      total: formattedOrders.length
    });
  } catch (error) {
    console.error('获取后厨订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败'
    });
  }
});

/**
 * 更新订单状态（后厨端）
 * PATCH /api/orders/:orderId/status
 */
router.patch('/:orderId/status', async (req, res) => {
  try {
    const { orderId } = req.params;
    const { status } = req.body;

    if (!status) {
      return res.status(400).json({
        success: false,
        message: '状态参数不能为空'
      });
    }

    const updatedOrder = await orderService.updateOrderStatus(orderId, status);

    // 实时推送状态变更到点菜窗口
    const io = req.app.get('io');
    if (io) {
      io.to('customer').emit('order-status-updated', {
        orderId: updatedOrder.id,
        status: updatedOrder.status,
        updatedAt: updatedOrder.updated_at
      });
    }

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: {
        id: updatedOrder.id,
        status: updatedOrder.status,
        updatedAt: updatedOrder.updated_at
      }
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新订单状态失败'
    });
  }
});

/**
 * 获取所有订单（管理端）
 * GET /api/orders/admin/list
 */
router.get('/admin/list', async (req, res) => {
  try {
    const { status, startDate, endDate, limit = 50, offset = 0 } = req.query;

    const filters = {
      status,
      startDate,
      endDate,
      limit: parseInt(limit),
      offset: parseInt(offset)
    };

    const orders = await orderService.getAllOrders(filters);

    const formattedOrders = orders.map(order => ({
      id: order.id,
      items: typeof order.items === 'string' ? JSON.parse(order.items) : order.items,
      totalPrice: order.total_price,
      userInfo: typeof order.user_info === 'string' ? JSON.parse(order.user_info) : order.user_info,
      status: order.status,
      createdAt: order.created_at
    }));

    res.json({
      success: true,
      data: formattedOrders,
      total: formattedOrders.length
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败'
    });
  }
});

/**
 * 计算订单价格（用于前端预览）
 * POST /api/orders/calculate
 */
router.post('/calculate', async (req, res) => {
  try {
    const { items } = req.body;

    if (!items || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '商品列表不能为空'
      });
    }

    const totalPrice = await orderService.calculateTotalPrice(items);

    res.json({
      success: true,
      data: {
        totalPrice
      }
    });
  } catch (error) {
    console.error('计算订单价格失败:', error);
    res.status(500).json({
      success: false,
      message: '计算价格失败'
    });
  }
});

/**
 * 删除订单（仅测试环境）
 * DELETE /api/orders/:orderId
 */
router.delete('/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params;

    const deleted = await orderService.deleteOrder(orderId);

    if (deleted) {
      res.json({
        success: true,
        message: '订单删除成功'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({
      success: false,
      message: '删除订单失败'
    });
  }
});

module.exports = router;